const Router = require('koa-router');
const router = new Router();
const tools = require("../../tools/tool");
const {db, QueryTypes} = require("../../models/db");
router.post('/list/kmye', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let excel = body.excel;
        let search = body.formData;
        let subjectId = search.subjectId ? search.subjectId : 0;
        let beginDate = body.beginDate
        let endDate = body.endDate
        let sql = `exec get_kmye @tenantId=${tenantId},@beginDate='${beginDate}',@endDate='${endDate}',@subjectId=${subjectId}`;
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if(i > 0) {
                let pid = tools.xe.toNumber(item.pid)
                if (pid) {
                    let initAmount = tools.xe.toNumber(item.initAmount)
                    let price1 = tools.xe.toNumber(item.price1)
                    let price2 = tools.xe.toNumber(item.price2)
                    let price1_all = tools.xe.toNumber(item.price1_all)
                    let price2_all = tools.xe.toNumber(item.price2_all)
                    let leftAmount = tools.xe.toNumber(item.leftAmount)
                    for (let idx = 0; idx < list.length; idx++) {
                        let it = list[idx];
                        let subId = tools.xe.toNumber(it.subId);
                        if (subId === pid) {
                            list[idx].initAmount = tools.xe.add(initAmount,it.initAmount)
                            list[idx].price1 = tools.xe.add(price1,it.price1)
                            list[idx].price2 = tools.xe.add(price2,it.price2)
                            list[idx].price1_all = tools.xe.add(price1_all,it.price1_all)
                            list[idx].price2_all = tools.xe.add(price2_all,it.price2_all)
                            list[idx].leftAmount = tools.xe.add(leftAmount,it.leftAmount)
                        }
                    }

                }
            }
        }
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            let direct = item.direct;
            let initAmount = tools.xe.toNumber(item.initAmount);
            let leftAmount = tools.xe.toNumber(item.leftAmount);
            if (initAmount === 0) {
                list[i].direct1 = '平';
            } else {
                list[i].direct1 = direct;
            }
            if (leftAmount === 0) {
                list[i].direct2 = "平";
            } else {
                list[i].direct2 = direct;
            }
        }

        if(excel) {
            return tools.doExcelOut(ctx, list, null)
        }
        else {
            return ctx.suc('', {
                total: 0,
                list
            })
        }
    } catch (e) {
        return ctx.err('无返回数据')
    }
})



module.exports = router;
